var Map2D = (function () {
	//初始化
	function Map2D() {
		//属性
		this.view = {};
		this.olmap = {};
		this.overlay = {};
		this.baselayers = [];
	
		this.init();
		//点击事件
		this.clickevent = {};

	};
	//
	Map2D.prototype.init = function (mapdiv) {

		var that = this;
		//微软影像
		var msaerial = new ol.layer.Tile({
				id: "msimg",
				visible: true,
				title: "微软影像",
				preload: Infinity,
				source: new ol.source.BingMaps({
					culture: "zh-cn",
					key: 'AnnJBLmScQLGhCET-i0R2hNlhBsnyR2pC2EXe4zCJrgWIIqbFToRle3Xwbiig6wK',
					imagerySet: "Aerial",
					// use maxZoom 19 to see stretched tiles instead of the BingMaps
					// "no photos at this zoom level" tiles
					maxZoom: 19
				})
			})
			this.baselayers.push(msaerial);
		//微软地形
		var msroadl = new ol.layer.Tile({
				id: "msvec",
				visible: false,
				title: "微软地形图",
				preload: Infinity,
				source: new ol.source.BingMaps({
					culture: "zh-cn",
					key: 'AnnJBLmScQLGhCET-i0R2hNlhBsnyR2pC2EXe4zCJrgWIIqbFToRle3Xwbiig6wK',
					imagerySet: "Road",
					// use maxZoom 19 to see stretched tiles instead of the BingMaps
					// "no photos at this zoom level" tiles
					maxZoom: 19
				})
			})
			this.baselayers.push(msroadl);
		//google影像
		var googleimg = new ol.layer.Tile({
				id: "googleimg",
				visible: false,
				preload: Infinity,
				title: "google地图",
				source: new ol.source.XYZ({
					urls: ['http://mt0.google.cn/vt/lyrs=y@177000000&,highlight:0x35f05296e7142cb9:0xb9625620af0fa98a@1|style:maps&hl=zh-CN&gl=CN&x={x}&y={y}&z={z}&s=Galil&src=app',
						'http://mt1.google.cn/vt/lyrs=y@177000000&,highlight:0x35f05296e7142cb9:0xb9625620af0fa98a@1|style:maps&hl=zh-CN&gl=CN&x={x}&y={y}&z={z}&s=Galil&src=app',
						'http://mt2.google.cn/vt/lyrs=y@177000000&,highlight:0x35f05296e7142cb9:0xb9625620af0fa98a@1|style:maps&hl=zh-CN&gl=CN&x={x}&y={y}&z={z}&s=Galil&src=app',
						'http://mt3.google.cn/vt/lyrs=y@177000000&,highlight:0x35f05296e7142cb9:0xb9625620af0fa98a@1|style:maps&hl=zh-CN&gl=CN&x={x}&y={y}&z={z}&s=Galil&src=app']
				})
			});
		//天地图地形
		var tiandituroad_layer = new ol.layer.Tile({
				id: "tdtvec",
				visible: false,
				preload: Infinity,
				title: "天地图路网",
				source: new ol.source.XYZ({
					urls: [
						"http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}",
						"http://t1.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}",
						"http://t2.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}",
						"http://t3.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}",
						"http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}",
						"http://t5.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}",
						"http://t6.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}",
						"http://t7.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}"],
					maxZoom: 18,
					minZoom: 2
				})
			});
		this.baselayers.push(tiandituroad_layer);

		var tianditusatellite_layer = new ol.layer.Tile({
				id: "tdtimg",
				visible: false,
				preload: Infinity,
				title: "天地图卫星影像",
				source: new ol.source.XYZ({
					urls: ['http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}',
						'http://t1.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}',
						'http://t2.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}',
						'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}',
						'http://t4.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}',
						'http://t5.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}',
						'http://t6.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}',
						'http://t7.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}'],
					maxZoom: 18,
					minZoom: 2
				})
			});
		this.baselayers.push(tianditusatellite_layer);

		var tiandituannotation = new ol.layer.Tile({
				id: "tdtcav",
				visible: false,
				preload: Infinity,
				title: "天地图文字标注",
				source: new ol.source.XYZ({
					urls: ['http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}',
						'http://t1.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}',
						'http://t2.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}',
						'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}',
						'http://t4.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}',
						'http://t5.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}',
						'http://t6.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}',
						'http://t7.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}'],
					maxZoom: 18,
					minZoom: 2
				})
			});

		this.baselayers.push(tiandituannotation);

		//this.baselayers[1].setVisible(true);
		// this.baselayers[2].setVisible(true);
		//弹出框
		var container = document.getElementById('popup2d');

		var mousePositionControl = new ol.control.MousePosition({
				projection: 'EPSG:4326',
				coordinateFormat: function (coordinate) {
					return ol.coordinate.format(coordinate, '经度：{x}   纬度：{y}', 6);
				},
				target: $('#coords').get(0),
				className: 'whatever-custom'
			});
		//@type {olx.OverlayOptions}

		this.poplayer = new ol.Overlay(({
					element: container,
					autoPan: true,
					autoPanAnimation: {
						duration: 250
					}
				}));

		var tooltip = document.getElementById('tooltip');
		this.tipslayer = new ol.Overlay({
				element: tooltip,
				offset: [10, 0],
				positioning: 'bottom-left'
		});

		/**
		 * Add a click handler to hide the popup.
		 * @return {boolean} Don't follow the href.
		 */

		this.view = new ol.View({
				center: ol.proj.transform([111.28, 30.70], 'EPSG:4326', 'EPSG:3857'),
				zoom: 2,
				minZoom: 2,
				maxZoom: 21
			});
		//如果旋转了。就关掉播放
        this.view.on("change:rotation", function (e) {

        });
		//初始化地图
		this.olmap = new ol.Map({
				target: 'map',
				// The DOM element that will contains the map
				renderer: 'canvas',
				// Force the renderer to be used
				layers: this.baselayers,
				overlays: [this.poplayer],
				// Create a view centered on the specified location and zoom level
				view: this.view

			});
			
		/*
		that.olmap.on('pointermove', function (evt) {

		var pixel = evt.pixel;
		var feature = that.olmap.forEachFeatureAtPixel(pixel, function (feature) {
		return feature;
		});

		tooltip.style.display = feature ? '' : 'none';
		if (feature) {
		var layerid = feature.layerid;
		tooltip.innerHTML =  feature.data[that.clickevent[layerid].title];
		that.tipslayer.setPosition(evt.coordinate);
		}
		});
		 */
		//点击事件处理

		that.olmap.on('singleclick', function (evt) {
			var coordinate = evt.coordinate;
			console.info(evt);
			////浏览
			//var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326'));
			var feature = that.olmap.forEachFeatureAtPixel(that.olmap.getEventPixel(evt.originalEvent), function (
						feature, layer) {
					return feature;
				});
			if (feature) {
				that.showpop({
					"feature": feature
				});
			} else {
				that.poplayer.setPosition(undefined);
			}
		});
	};
	/*
	 * 关闭提示框
	 */
	Map2D.prototype.closepop = function () {
		this.poplayer.setPosition(undefined);
	}
	/*
	 * 打开提示框
	 */
	Map2D.prototype.showpop = function (options) {
		var that = this;
		var feature = options.feature;
		var geom = feature.getGeometry();

		var coordinate = {};
		if (feature.getGeometry().getType() === 'Point') {
			coordinate = feature.getGeometry().getCoordinates();
		} else {
			coordinate = ol.extent.getCenter(feature.getGeometry().getExtent());
		}

		var layerid = feature.layerid;
		var content = document.getElementById('popup-content2d');
		if (layerid && that.clickevent[layerid]) {

			if (that.clickevent[layerid].url != "") {
				var url = Mustache.render(that.clickevent[layerid].url, feature.data);

				$.get(url, function (e) {
					var contentdata = Mustache.render(e, feature.data);
					content.innerHTML = contentdata; // '<p>军事基地:</p><code>'+ content+  '</code>';
					that.poplayer.setPosition(coordinate);
					if (that.clickevent[layerid].script) {
						that.clickevent[layerid].script(feature.data);
					}
				});
				//修改表头
				$("#popup2dtitle").html(feature.data[that.clickevent[layerid].title]);
			} else {
				var contentdata = Mustache.render(that.clickevent[layerid].template, feature.data);
				content.innerHTML = contentdata; // '<p>军事基地:</p><code>'+ content+  '</code>';
				that.poplayer.setPosition(coordinate);
			}
			var closer2d = $('#popcloser2d');
			closer2d.on("click", function (e) {
				that.poplayer.setPosition(undefined);
				closer2d.blur();
				return false;
			});
		}
	}
	//点击事件代码比较多，单独提出来
	Map2D.prototype.clicks = function (options) {
		//每个图层点击在自己图层写，然后传进来，统一显示和处理
		this.clickevent[options.layerid] = options;
	};

	//设定可见性
	Map2D.prototype.setlayervisible = function (options) {
		var layers = this.olmap.getLayers();
		var length = layers.getLength();
		for (var i = 0; i < length; i++) {
			if (options.layerid === layers.item(i).get('id')) {
				layers.item(i).setVisible(options.visible);
				break;
			}
		}
		return null;
	};
	//设定可见性
	Map2D.prototype.getlayervisible = function (options) {
		var layers = this.olmap.getLayers();
		var length = layers.getLength();
		for (var i = 0; i < length; i++) {
			if (options.layerid === layers.item(i).get('id')) {
				return layers.item(i).getVisible();
				break;
			}
		}
		return false;
	};
	//获取图层
	Map2D.prototype.getlayerbyid = function (options) {
		//console.info(layerId);
		var layers = this.olmap.getLayers();
		var length = layers.getLength();
		for (var i = 0; i < length; i++) {
			//console.info(layers.item(i).get('id'));
			if (options.layerid === layers.item(i).get('id')) {
				return layers.item(i);
			}
		}
		return null;
	};

	//删除图层
	Map2D.prototype.removelayerbyid = function (options) {
		var layers = this.olmap.getLayers();
		var length = layers.getLength();
		for (var i = 0; i < length; i++) {
			if (options.layerid === layers.item(i).get('id')) {
				this.olmap.removeLayer(layers.item(i));
			}
		}
		return null;
	};
	//设定对象，并居中
	Map2D.prototype.setfeaturecenter = function (options) {
		var layers = this.olmap.getLayers();
		var layer;
		var length = layers.getLength();
		for (var i = 0; i < length; i++) {
			if (options.layerid == layers.item(i).get('id')) {
				layer = layers.item(i);
			}
		}
		if (layer) {
			var sources = layer.getSource();
			if (sources) {
				var features = sources.getFeatures();
				for (var i = 0; i < features.length; i++) {
					var tmpvalue = features[i][options.featurename];
					//console.info(features[i]);
					if (tmpvalue == options.featurevalue) {
						var feature = features[i];
						var polygon = /** @type {ol.geom.SimpleGeometry} */(feature.getGeometry());
						var size = /** @type {ol.Size} */(this.olmap.getSize());
						//console.info(polygon);
						//var extent = polygon.getExtent();
						//this.olmap.getView().fit(polygon.getExtent(), this.olmap.getSize());
						this.olmap.getView().setZoom(11);
						this.olmap.getView().animate({
							center: polygon.flatCoordinates,
							duration: 1000
						});
						this.showpop({
							"feature": feature
						});
						return;
					}
				}
			}
		}
	};
	//获取数据
	Map2D.prototype.dataview = function (options) {
		if (this.layers[datatype]) {
			this.layers[datatype].show = true;
		}
	};
	//修改底图
	Map2D.prototype.setbasemap = function (options) {
		var len = this.baselayers.length;
		for (var i = 0; i < len; i++) {
			if (this.baselayers[i].get("id") === options.layerid) {
				this.baselayers[i].setVisible(true);
			} else {
				this.baselayers[i].setVisible(false);
			}
		}
	};
	//保存图片
	Map2D.prototype.save = function () {
		this.olmap.once('postcompose', function (event) {
			var canvas = event.context.canvas;
			canvas.toBlob(function (blob) {
				saveAs(blob, 'map.png');
			});
		});
		this.olmap.renderSync();
	}
	//返回
	return Map2D;
})();
